package com.hoopchina.util.update;

import java.io.IOException;
import java.net.URLConnection;

import com.hoopchina.news.R;
import com.hoopchina.util.download.DownloadCallback;
import com.hoopchina.util.download.DownloadTask;
import com.hoopchina.util.download.Downloader;
import com.hoopchina.util.xml.XMLDataNetwork;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;

public class Update {
    private static final String TAG      = "Update";
    private String              mApkPath = "/sdcard/baidunews/apk";
    private String              mApkName = null;
    private Context             parent   = null;
    public static VersionInfo   mVerInfoXML;
    public static VersionInfo   mVerInfoLocal;

    public Update( Context acontext ) {
        parent = acontext;
    }

    public boolean needUpdate() {
        this.getXmlInfo();
        this.getLocalInfo();
        try {
            String aXML[] = mVerInfoXML.getVerName().split( "\\." );
            String aLoc[] = mVerInfoLocal.getVerName().split( "\\." );
            Log.i( TAG, "aXML[].length = " + aXML.length );
            Log.i( TAG, "aLoc[].length = " + aLoc.length );

            for ( int i = 0; i < ( aXML.length < aLoc.length ? aXML.length : aLoc.length ); i++ ) {
                Log.i( TAG, "mVerInfoXML.verName.aXML[" + i + "] = " + aXML[i] );
                Log.i( TAG, "mVerInfoLocal.verName.aLoc[" + i + "] = " + aLoc[i] );
                if ( Integer.parseInt( aXML[i] ) > Integer.parseInt( aLoc[i] ) )
                    return true;
            }
        }
        catch ( NullPointerException e ) {
            e.printStackTrace();
        }
        catch ( ArrayIndexOutOfBoundsException e ) {
            e.printStackTrace();
        }

        return false;
    }

    public void downloadNewApk( final Context context ) {

        Log.i( TAG, "downloadNewApk() in" );
        Toast.makeText( context, context.getString( R.string.app_download_start ), 500 ).show();
        String url = mVerInfoXML.getApkURL();
        mApkName = url.substring( url.lastIndexOf( "/" ) + 1 );
        Log.i( TAG, "mApkurl = " + url );
        Log.i( TAG, "mApkName = " + mApkName );
        try {
            Downloader.getInstance().download( url, mApkPath, new DownloadCallback() {

                @Override
                public void onFinished( DownloadTask finishedTask ) {
                    String uri = "file://" + mApkPath + "/" + mApkName;
                    Log.i( TAG, "download finished, uri=" + uri );
                    Intent intent = new Intent( Intent.ACTION_VIEW );
                    intent.setDataAndType( Uri.parse( uri ),
                            "application/vnd.android.package-archive" );
                    parent.startActivity( intent );
                }

                @Override
                public void onFailed() {
                }
            } );

        }
        catch ( Exception e ) {
            e.printStackTrace();
        }
    }

    private void getLocalInfo() {
        Log.i( TAG, "getLocalInfo IN" );
        PackageManager manager = this.parent.getPackageManager();
        try {
            PackageInfo pInfo = manager.getPackageInfo( this.parent.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS );
            mVerInfoLocal = new VersionInfo();
            // mVerInfoLocal.setVerCode(pInfo.lastUpdateTime);
            mVerInfoLocal.setVerName( pInfo.versionName );

        }
        catch ( NameNotFoundException e ) {
            e.printStackTrace();
        }
        Log.i( TAG, "getLocalInfo OUT" );
    }

    private void getXmlInfo() {
        Log.i( TAG, "getCodeXML() IN" );
        try {
            // String url = parent.getString(R.string.)
            // + "version.xml";
            String url = "http://nuub032.chinaw3.com/android/version.xml";
            URLConnection urlConn_source = XMLDataNetwork.getHttpConnection( url );
            mVerInfoXML = new VersionInfo();
            UpdateDetailXML pull = new UpdateDetailXML();
            mVerInfoXML = pull.getUpdateInfo( urlConn_source.getInputStream() );
            if ( urlConn_source != null && urlConn_source.getInputStream() != null ) {
                urlConn_source.getInputStream().close();
            }

        }
        catch ( IOException e ) {
            e.printStackTrace();
        }
        catch ( OutOfMemoryError error ) {
            error.printStackTrace();
        }
        catch ( Exception e ) {
            e.printStackTrace();
        }
        Log.i( TAG, "getCodeXML() OUT" );
    }
}